import { session } from 'electron'

class MockApi {
  static mockEnabled = true
  static mockRules = [] as any
  // 初始化请求拦截器
  static initRequestInterceptor() {
    const ses = session.defaultSession

    // 拦截所有HTTP请求
    ses.webRequest.onBeforeRequest({ urls: ['<all_urls>'] }, (details, callback: any) => {
      // 如果Mock功能关闭，直接放行
      if (!this.mockEnabled) {
        return callback({ cancel: false })
      }

      // 查找匹配的Mock规则
      const matchedRule = this.findMatchedRule(details)

      if (matchedRule) {
        // 命中规则，返回Mock数据
        const response = this.createMockResponse(matchedRule)
        return callback({
          cancel: true,
          respondWith: response
        })
      }

      // 未命中规则，放行请求
      callback({ cancel: false })
    })
  }

  // 查找匹配的Mock规则
  static findMatchedRule(details) {
    return this.mockRules.find((rule: any) => {
      // 方法匹配（不区分大小写）
      const methodMatch =
        rule.method.toLowerCase() === details.method.toLowerCase() || rule.method === 'ANY'

      // URL匹配（支持通配符*）
      const urlPattern = new RegExp(`^${rule.url.replace(/\*/g, '.*')}$`)
      const urlMatch = urlPattern.test(details.url)

      return methodMatch && urlMatch
    })
  }

  // 创建Mock响应
  static createMockResponse(rule) {
    try {
      // 解析Mock数据（支持JSON字符串或对象）
      const data = typeof rule.response === 'string' ? JSON.parse(rule.response) : rule.response

      return {
        statusCode: rule.statusCode || 200,
        headers: {
          'Content-Type': rule.contentType || 'application/json',
          ...rule.headers
        },
        data: Buffer.from(JSON.stringify(data))
      }
    } catch (error: any) {
      console.error('Mock响应解析失败:', error)
      return {
        statusCode: 500,
        headers: { 'Content-Type': 'application/json' },
        data: Buffer.from(
          JSON.stringify({
            error: 'Mock数据格式错误',
            details: error.message
          })
        )
      }
    }
  }
  // 获取所有规则
  static getMockRules() {
    return this.mockRules
  }
  //   // 添加新规则
  static addMockRules(rule: any) {
    rule.id = Date.now().toString()
    this.mockRules.unshift(rule)
    return this.mockRules
  }
  // 更新规则
  static updateMockRules(updatedRule: any) {
    this.mockRules = this.mockRules.map((rule) => (rule.id === updatedRule.id ? updatedRule : rule))
    return this.mockRules
  }
  // 删除规则
  static deleteMockRules(id: string) {
    this.mockRules = this.mockRules.filter((rule) => rule.id !== id)
    return this.mockRules
  }
  // 切换Mock开关
  static toggleMockEnabled(enabled) {
    this.mockEnabled = enabled
    return this.mockEnabled
  }

  // 获取Mock状态
  static getMockEnabled() {
    return this.mockEnabled
  }
}
export default MockApi
